package com.crazymaker.springcloud.common.context;

import com.crazymaker.springcloud.common.constants.SessionConstants;
import org.springframework.core.NamedThreadLocal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionHolder {

    /**
     * session id本地变量
     */
    private static final ThreadLocal<String> sidLocal = new NamedThreadLocal<>("sidLocal");

    private static ThreadLocal<String> sessionIDStore = new NamedThreadLocal<>("sessionIDStore");

    private static ThreadLocal<String> userIdentiferLocal = new NamedThreadLocal<>("userIdentiferLocal");

    private static ThreadLocal<HttpSession> sessionLocal = new NamedThreadLocal<>("sessionLocal");

    private static ThreadLocal<HttpServletRequest> requestThreadLocal = new NamedThreadLocal<>("requestThreadLocal");

    public static final String G_USER = "USER-CACHE";

    public static String getSessionIDStore() {
        if (null != sessionIDStore.get()) {
            return sessionIDStore.get();
        }
        return SessionConstants.SESSION_STORE;
    }

    public void setSessionIDStore(String sessionIDStoreStr) {
        sessionIDStore.set(sessionIDStoreStr);
    }

    public static void setUserIdentifer(String userIdentifier) {
        userIdentiferLocal.set(userIdentifier);
    }

    public static String getUserIdentifer() {
        return userIdentiferLocal.get();
    }

    public static String getSid() {
        return sidLocal.get();
    }

    public static void setSid(String sid) {
        sidLocal.set(sid);
    }

    public static HttpSession getSession() {
        return sessionLocal.get();
    }

    public static void setSession(HttpSession session) {
        sessionLocal.set(session);
    }

    public static HttpServletRequest getRequest() {
        return requestThreadLocal.get();
    }

    public static void setRequest(HttpServletRequest request) {
        requestThreadLocal.set(request);
    }
}
